package com.gzyct.m.api.common.partner;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;

import org.springframework.cache.ehcache.EhCacheCache;
import org.springframework.cache.ehcache.EhCacheManagerUtils;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.core.io.ClassPathResource;

public class PartnerCache {

	private static PartnerCache instance = new PartnerCache();

	private EhCacheCache ehCacheCache = null;

	private CacheManager cacheManager = null;

	private PartnerCache() {
		initCache();
	}

	public static PartnerCache getInstantce() {
		return instance;
	}

	public <T> T get(Class<T> type, Object... params) {
		return ehCacheCache.get(SimpleKeyGenerator.generateKey(params), type);
	}

	public void put(Object value, Object... params) {
		ehCacheCache.put(SimpleKeyGenerator.generateKey(params), value);
	}

	private void initCache() {
		Configuration configuration = EhCacheManagerUtils.parseConfiguration(new ClassPathResource(
				"yctapi-common-ehcache.xml"));
		configuration.setName("yctapi-common-ehcache");
		cacheManager = CacheManager.create(configuration);
		Cache cache = cacheManager.getCache("yctapi-common-partner");
		ehCacheCache = new EhCacheCache(cache);
	}

	private void shutdownCache() {
		if (cacheManager != null) {
			cacheManager.shutdown();
		}
	}

	@Override
	protected void finalize() throws Throwable {
		shutdownCache();
		super.finalize();
	}

}
